/*
* name: scroll-row
* version: v1.1.2
* update: event未定义错误
* date:2014-12-17
*/
define(function(require, exports, module) {
	var $ = require('jquery');
	$.fn.scrollrow = function(config) {
		var opt = {
				up: null,
				down: null,
				wrap:'ul',
				cell:'li',
				line: 1,
				speed: 500,
				auto: true,
				time: 5e3,
				callback: function(nowRow){},
				ext: function(totalRow){}
			},
			$this = $(this),
			$wrap, $cell, nowRow = 1, _T, lasted, scrollUp, scrollDown, _btnUp, _btnDown;
		if(!$this.length) return;	
		$.extend(opt, config || {}, $(this).data('config') || {});
		//添加左右按钮
		if ($(opt.up).length && $(opt.down).length) {
			_btnUp = $(opt.up);
			_btnDown = $(opt.down);
		} else {
			$this.append('<a class="arrs arr_prev" /> <a class="arrs arr_next" />');
			_btnUp = $this.children(".arr_prev");
			_btnDown = $this.children(".arr_next");
		};
		$wrap = $this.find(opt.wrap);
		$cell = $wrap.find(opt.cell);
		lineH = $cell.outerHeight(true);
		cols = Math.floor($this.width() / $cell.outerWidth()) ? Math.floor($this.width() / $cell.outerWidth()) : 1;
		rows = Math.floor($this.height() / lineH);
		rowsall = Math.ceil($cell.length / cols);
		line = opt.line > rows ? rows : opt.line;
		upHeight = 0 - line * lineH;
		totalRow = Math.ceil(rowsall / rows);
		//运行条件检测
		if (rowsall * lineH <= $this.height()) {
			_btnUp.addClass('unable');
			_btnDown.addClass('unable');
			opt.ext && opt.ext(totalRow);
			if(window.console){
				console.log("scroll-row: lines no enough to scroll.");
			};	
			return $this;
		};
		
		scrollDown = function(e) {
			e && e.preventDefault();
			$wrap.stop(1).animate({marginTop: upHeight}, opt.speed, function() {
				$wrap.css('marginTop', 0);
				for (i = 1; i <= line; i++) {
					$this.find(opt.cell + ":lt(" + cols + ")").appendTo($wrap);
				}
			});
			nowRow = (nowRow <= 1 ? totalRow : nowRow - 1);
			opt.callback && opt.callback(nowRow);
		};
		
		scrollUp = function(e) {
			e && e.preventDefault();
			lasted = $cell.length - cols - 1;
			for (i = 1; i <= line; i++) {
				$this.find(opt.cell + ":gt(" + lasted + ")").show().prependTo($wrap)
			};
			$wrap.stop(1).css('marginTop', upHeight).animate({marginTop: 0}, opt.speed);
			nowRow = (nowRow >= totalRow ? 1 : nowRow + 1);
			opt.callback && opt.callback(nowRow);
		};
		
		if (opt.auto) {
			_T = setInterval(function() {scrollDown()}, opt.time);
			$this.hover(function() {
				clearInterval(_T)
			}, function() {
				_T = setInterval(function() {scrollDown()}, opt.time)
			})
		};
		
		_btnUp.click(function(e) {
			scrollUp(e)
		});
		_btnDown.click(function(e) {
			scrollDown(e)
		});
		
		opt.ext && opt.ext(totalRow);
		
		return $this;
	};
})